/*
 * @Date: 2020-02-19 13:35:19
 * @名称: 阅读漫画页面 - 控制器
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-08-23 00:16:58
 * @FilePath: /bica_acg/lib/Pages/ReadingComics/ReadingComicsController.dart
 */
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pica_acg/DataBaseFunction.dart';
import 'package:pica_acg/GlobalFunction.dart';
import 'package:pica_acg/GlobalNetWorkReturnDefind.dart';
import 'package:pica_acg/GlobalSettings.dart';
import 'package:pica_acg/GlobalVarlable.dart';
import 'package:pica_acg/GlobalWidget.dart';
import 'package:pica_acg/Pages/ReadingComics/Widget/ReadingComicsBody/ReadingComicsBodyController.dart';
import 'package:pica_acg/Pages/ReadingComics/Widget/ReadingComicsBox/ReadingComicsBoxController.dart';
import 'package:pica_acg/Pages/ReadingComics/Widget/Tips/ReadingComicsTipsController.dart';
import 'package:pica_acg/tools/NetWorkController.dart';
import 'package:pica_acg/tools/extends/Json/ComicsInfo/ComicsInfoListJson.dart';

class ReadingComicsController extends StatefulWidget {
  ReadingComicsController({
    Key key,
    this.context,
    this.pageName,
    this.comicsName,
    this.comicsId,
    this.subsectionId,
  }) : super(key: key);
  final BuildContext context;
  final String pageName; //第几话名字
  final String comicsName; //漫画名
  final String comicsId; //漫画id - 分享用
  final String subsectionId; //分卷id
  @override
  ReadingComicsControllerState createState() => ReadingComicsControllerState();
}

var readingComicsState =
    new GlobalKey<ReadingComicsControllerState>(); //漫画显示控制器

bool readingComicsReadingComicsBoxControllerVisible =
    $global_ReadingComicsOpenComicsViewBoxHide; //是否隐藏框架
bool readingComicsReadingComicsTipsControllerVisible = false; //是否隐藏提示
List bookDownloadChapterImagesList;
ComicsInfoListJson netWorkComicsinfoEpisodes; //初始数据

class ReadingComicsControllerState extends State<ReadingComicsController> {
  @override
  void initState() {
    super.initState();

    if (setting.screenOrientation == 0) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
    } else {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeRight,
        DeviceOrientation.landscapeRight,
      ]);
    }
    netWorkComicsinfoEpisodes =
        ComicsInfoListJson.fromJson($netWorkComicsinfoEpisodes);
    dataBaseSelect(
      //判断这个分节有没有下载
      "BookDownloadChapterImagesList",
      'BookId = ? and ChapterId = ?',
      [
        widget.comicsId,
        widget.subsectionId,
      ],
    ).then((dataBaseBookDownloadChapterImagesList) {
      if (dataBaseBookDownloadChapterImagesList.length == 0) {
        //没有下载的话
        NetWorkController.get(
          getComicsInfoEpisodes(
                '${widget.comicsId}',
                '${widget.subsectionId}',
              ) +
              '&page=1',
          (callBack) {
            var tempCallBack = ComicsInfoListJson.fromJson(callBack);
            if (tempCallBack.code == "200") {
              netWorkComicsinfoEpisodes = ComicsInfoListJson.fromJson(callBack);
              allPage = netWorkComicsinfoEpisodes.data.pages.docs.length;

              localData = false;
              if (netWorkComicsinfoEpisodes.data.pages.docs.length == 0) {
                //判断有没有正确获取数据
                Navigator.of(context).push(
                  PageRouteBuilder(
                    pageBuilder: (context, _, __) => Container(
                      child: GlobalTipsExtend(
                        body: 'a',
                        height: 500,
                        logo: {
                          'isLogo': true,
                          'logoSrc': 'images/Tisp/UnknownError.png'
                        },
                        expand: true,
                        expButton: {
                          "isExpButton": false,
                          "expButtonSuccessName": 'aaaa',
                          "expButtonSuccessOntab": () {
                            Navigator.pop(context);
                          },
                          "expButtonErrorName": 'aaaa',
                          "expButtonErrorOntab": () {
                            Navigator.pop(context);
                          },
                        },
                        expandBody: Container(
                          margin: EdgeInsets.only(
                            top: ScreenUtil().setHeight(600),
                          ),
                          height: ScreenUtil().setHeight(100),
                          alignment: Alignment.center,
                          child: ClipRRect(
                            borderRadius: new BorderRadius.vertical(),
                            child: SingleChildScrollView(
                              child: Column(
                                children: [
                                  SizedBox(
                                    child: Text(
                                      '遇到异常，请稍后再试',
                                      softWrap: true,
                                      style: TextStyle(
                                        // fontWeight: FontWeight.w700,
                                        fontSize: 14.0,
                                        color: Color.fromRGBO(79, 79, 79, 1),
                                        decoration: TextDecoration.none,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    opaque: false,
                  ),
                );
              }
              setState(() {});
            } else {
              //获取失败 没有章节或者没有这一子节操作

              Navigator.of(context).push(
                PageRouteBuilder(
                  pageBuilder: (context, _, __) => GlobalTips(
                    body: '暂时无法查看本章节 错误代码 ${tempCallBack.error}',
                    height: ScreenUtil().setHeight(900),
                    imageAsset: 'images/Tisp/Error.png',
                  ),
                  opaque: false,
                ),
              );
            }
          },
          headers: getApiRequestHeadrs("ComicsEpisodes"),
        );
      } else {
        bookDownloadChapterImagesList = dataBaseBookDownloadChapterImagesList;
        allPage = bookDownloadChapterImagesList.length;
        localData = true;
        setState(() {});
      }
    });
  }

  bool localData = false;
  int allPage = 1;
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: Scaffold(
        body: SingleChildScrollView(
          physics: NeverScrollableScrollPhysics(),
          child: Container(
            child: Stack(
              children: <Widget>[
                Container(
                  color: Color(0xff050000),
                  width: ScreenUtil().setWidth(750),
                  height: ScreenUtil().setHeight(1334),
                ),
                GestureDetector(
                  child: ReadingComicsReadingComicsBodyController(
                    localData: localData,
                    bookDownloadChapterImagesList:
                        bookDownloadChapterImagesList, //数据库中下载的记录
                    allPage: allPage, //网络的全部页数
                    comicsinfoEpisodesList: netWorkComicsinfoEpisodes,
                    key: globalKeyReadingComicsReadingComicsBodyControllerState,
                    parentWindowID: context,
                    comicsId: widget.comicsId, //漫画id
                    subsectionId: widget.subsectionId, //分卷id
                  ),
                  onTap: () {
                    readingComicsReadingComicsBoxControllerVisible =
                        !readingComicsReadingComicsBoxControllerVisible;
                    setState(() {});
                  },
                ),
                Visibility(
                  //整体框架
                  visible: readingComicsReadingComicsBoxControllerVisible,
                  child: ReadingComicsReadingComicsBoxController(
                    allPage: allPage,
                    key: globalKeyReadingComicsReadingComicsBoxControllerState,
                    context: widget.context,
                    pageName: widget.pageName,
                    comicsName: widget.comicsName,
                    comicsId: widget.comicsId, //漫画id
                    subsectionId: widget.subsectionId, //分卷id
                  ),
                ),
                Visibility(
                  //提示
                  visible: readingComicsReadingComicsTipsControllerVisible,
                  child: ReadingComicsReadingComicsTipsController(),
                ), //这个一定要在最后 因为这是 在顶层的
              ],
            ),
          ),
        ),
      ),
    );
  }

  isItHiddenTips() {
    //是否隐藏提示
    readingComicsReadingComicsTipsControllerVisible =
        !readingComicsReadingComicsTipsControllerVisible;
    setState(() {});
  }
}
